package com.bbs.service.impl;

import com.bbs.exception.BusinessException;
import com.bbs.fegin.UserClient;
import com.bbs.pojo.Result;
import com.bbs.pojo.User;
import com.bbs.pojo.UserPrincipal;
import com.bbs.security.TokenProvider;
import com.bbs.service.AuthenticationService;
import com.bbs.service.dto.CredentialDto;
import com.bbs.utils.Constants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Service
public class AuthenticationServiceImpl implements AuthenticationService {
    @Autowired
    UserClient userClient;
    @Autowired
    TokenProvider tokenProvider;

    @Override
    public String authenticate(CredentialDto credentialDto) {
        Result<User> result = userClient.getUser(credentialDto.getUsername());
        if(result == null || result.getData() == null){
            throw new BusinessException(Constants.FORBIDDEN_MESSAGE, Constants.FORBIDDEN_CODE);
        }
        User user = result.getData();

        //密码比对
        if(!Objects.equals(credentialDto.getPassword(), user.getPassword())){
            throw new BusinessException(Constants.FORBIDDEN_MESSAGE, Constants.FORBIDDEN_CODE);
        }

        //生成Token
        UserPrincipal userPrincipal = new UserPrincipal();
        userPrincipal.setUserId(user.getUserId());
        userPrincipal.setUsername(user.getUsername());
        userPrincipal.setRole(user.getRole());

        return tokenProvider.createToken(userPrincipal, credentialDto.getRememberMe());
    }
}
